Page({
  data: {
    detail: null
  },

  onLoad(options) {
    this.loadNoticeDetail(options.id);
  },

  // 加载通知详情
  loadNoticeDetail(id) {
    wx.showLoading({ title: '加载中' });
    wx.request({
      url: 'http://192.168.172.134:5000/api/notification',
      method: 'GET',
      data: { id: id },
      success: (res) => {
        if (res.data.code === 200) {
          const detail = res.data.data;
          
          // 解析JSON字符串
          try {
            detail.attachments = JSON.parse(detail.attachments || '[]');
          } catch (e) {
            console.error('附件解析失败', e);
            detail.attachments = [];
          }

          this.setData({ detail });
        }
      },
      complete: () => wx.hideLoading()
    });
  },

  // 下载文件
  downloadFile(e) {
    const { url, name } = e.currentTarget.dataset;
    wx.showLoading({ title: '下载中...' });

    wx.downloadFile({
      url: url,
      success(res) {
        if (res.statusCode === 200) {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            showMenu: true,
            success() {
              console.log('打开文档成功');
            },
            fail(err) {
              wx.showToast({ title: '暂不支持此文件类型', icon: 'none' });
            }
          })
        }
      },
      fail(err) {
        wx.showToast({ title: '下载失败', icon: 'none' });
      },
      complete: () => wx.hideLoading()
    });
  },

  // 时间格式化
  formatDate(timestamp) {
    const date = new Date(timestamp);
    const addZero = n => n < 10 ? '0' + n : n;
    return `${date.getFullYear()}-${addZero(date.getMonth() + 1)}-${addZero(date.getDate())} ${addZero(date.getHours())}:${addZero(date.getMinutes())}`;
  }
});